from werkzeug.security import generate_password_hash, check_password_hash
from app.extensions import db


class Website(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category', back_populates='websites')


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    websites = db.relationship('Website', back_populates='category')


class Software(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    version = db.Column(db.String(30))
    path = db.Column(db.String(128))
    slug = db.Column(db.String(16))
    status = db.Column(db.Integer, default=0)     # 安装状态
    describe = db.Column(db.String(256))
    cmd = db.relationship('Command', uselist=False)


class Command(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    install = db.Column(db.String(128))
    secondary = db.Column(db.String(128))   # 主要用于安装第二个PHP
    uninstall = db.Column(db.String(128))
    software_id = db.Column(db.Integer, db.ForeignKey('software.id'))
    software = db.relationship('Software')


class Admin(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20))
    password_hash = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)

